<script setup>
// 发送短信验证码组件
import {ref} from 'vue'
import {validateMobile, validateEmail} from "@/utils/validate.js";
import {httpPost} from "@/utils/http.js";
import {ElMessage} from "element-plus";

const props = defineProps({
  receiver: String, // 接收者，表示手机号或者邮箱
  size: String,
  type: { // 类型，手机号或者邮箱
    type: String,
    default: 'mobile'
  }
})
// 按钮名称
const btnText = ref('发送验证码')
// 按钮是否能够点击
const canSend = ref(true)
const sendMsg = () => {
  // 验证码手机号是否合法
  if (!validateMobile(props.receiver) && props.type === 'mobile') {
    return ElMessage.error('请输入合法的手机号')
  }
  // 验证邮箱是否合法
  if (!validateEmail(props.receiver) && props.type === 'email') {
    return ElMessage.error('请输入合法的邮箱地址')
  }
  doSendMsg()
}

const doSendMsg = () => {
  if (!canSend.value) {
    return
  }

  canSend.value = false
  httpPost('api/sms/send_code', {receiver: props.receiver}).then(() => {
    ElMessage.success('验证码发送成功')
    let time = 60
    btnText.value = time
    // 定时器用来修改按钮的值，进行按钮倒计时显示
    const handler = setInterval(() => {
      time = time - 1
      if (time <= 0) {
        clearInterval(handler)
        btnText.value = '重新发送'
        canSend.value = true
      } else {
        btnText.value = time
      }
    }, 1000)
  }).catch(e => {
    canSend.value = true
    ElMessage.error('验证码发送失败：' + e.message)
  })
}

</script>

<template>
  <el-container class="send-verify-code">
    <el-button type="success" :size="props.size" :disabled="!canSend" @click="sendMsg">
      {{btnText}}
    </el-button>
  </el-container>
</template>

<style scoped lang="stylus">

.send-verify-code {
  .send-btn {
    width: 100%;
  }
}
</style>